<template>
  <div>
    <div class="head">
      <div class="head_left">
        <el-form :model="searchForm" :inline="inline">
          <el-form-item label="满额限制">
            <el-select
              v-model="searchForm.type"
              placeholder="请选择"
              style="margin-left:10px"
              clearable
            >
              <el-option label="全部" value="null"></el-option>
              <el-option label="满减型" value="0"></el-option>
              <el-option label="无门栏" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品限制">
            <el-select
              v-model="searchForm.limitType"
              placeholder="请选择"
              style="margin-left:10px"
              clearable
            >
              <el-option label="全部" value="null"></el-option>
              <el-option label="无限制" value="0"></el-option>
              <el-option label="限制活动" value="1"></el-option>
              <el-option label="限制商品" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标题">
            <el-input
              placeholder="优惠券标题"
              v-model="searchForm.title"
              style="width:200px;margin-left:10px"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button size="small" @click="getData" style="margin-left:30px">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div>
        <el-button size="mini" type="primary" @click="openAddForm">添加</el-button>
      </div>
    </div>

    <el-table :data="tableData" border>
      <el-table-column label="ID" align="center" width="50px">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.title}}</span>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="限制金额" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.limitType}}</span>
        </template>
      </el-table-column>
      <el-table-column label="限制商品" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.condition}}</span>
        </template>
      </el-table-column>
      <el-table-column label="领取/总发放" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.obtainRate}}</span>
        </template>
      </el-table-column>
      <el-table-column label="已使用" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.useNum}}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.createTime}}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status==0">正常</el-tag>
          <el-tag type="danger" v-if="scope.row.status==1">作废</el-tag>
          <el-tag type="warning" v-if="scope.row.status==2">过期</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status==0"
            type="danger"
            size="mini"
            @click="updateStatus(scope.row.id)"
          >作废</el-button>
          <el-button
            v-if="scope.row.status!=0"
            type="danger"
            size="mini"
            @click="del(scope.row.id)"
          >删除</el-button>
          <el-button type="primary" size="mini" @click="query(scope.row.id)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page="index"
        :page-size="pageSize"
        :page-sizes="[10,20]"
        layout="total,sizes,prev, pager, next,jumper"
        :total="total"
      ></el-pagination>
    </div>
    <el-dialog :title="title" :visible.sync="visible" width="800px">
      <div class="dialog">
        <el-form label-width="100px" class="form" :rules="rules" :model="form" ref="from">
          <el-form-item label="优惠券名称" prop="title">
            <el-input placeholder="输入优惠券名称" v-model="form.title" :disabled="title=='修改'" />
          </el-form-item>
          <el-form-item label="满减类型" prop="type">
            <el-radio-group v-model="form.type" :disabled="title=='修改'">
              <el-radio :label="0">满减型</el-radio>
              <el-radio :label="1">无门栏</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="优惠券金额" prop="amount">
            <el-input placeholder="输入优惠券金额" v-model="form.amount" :disabled="title=='修改'" />
          </el-form-item>
          <el-form-item v-if="form.type==0" label="优惠券满减">
            <el-input
              placeholder="输入优惠券满减金额"
              v-model="form.conditionAmount"
              :disabled="title=='修改'"
            />
          </el-form-item>
          <el-form-item label="过期类型" prop="expireType">
            <el-radio-group v-model="form.expireType" :disabled="title=='修改'">
              <el-radio :label="0">自定义</el-radio>
              <el-radio :label="1">领取天数</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.expireType==1" label="领取天数">
            <el-input placeholder="输入领取过期天数" v-model="form.expireDays" :disabled="title=='修改'" />
          </el-form-item>
          <el-form-item v-if="form.expireType==0" label="自定义">
            <el-date-picker
              format="yyyy-MM-dd"
              v-model="form.time"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :disabled="title=='修改'"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="发放量" prop="limitSendTotal">
            <el-input placeholder="输入发放量" v-model.number="form.limitSendTotal" />
          </el-form-item>
          <el-form-item label="领取量" prop="limitPre">
            <el-input placeholder="输入每人领取数量" v-model.number="form.limitPre" />
          </el-form-item>
          <el-form-item label="说明" prop="explainText">
            <el-input placeholder="输入优惠券说明" v-model="form.explainText" type="textarea" :rows="4" />
          </el-form-item>
          <el-form-item label="限制类型" prop="limitType">
            <el-radio-group v-model="form.limitType" :disabled="title=='修改'">
              <el-radio :label="0">无限制</el-radio>
              <el-radio :label="1">限制活动</el-radio>
              <el-radio :label="2">限制商品</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.limitType!=0 &&title=='添加'">
            <el-button type="primary" size="mini" @click="openChoise">选择</el-button>
            <span style="color:#909399;margin-left:15px;font-size:10px">{{choiceText}}</span>
          </el-form-item>
        </el-form>
        <div class="bottom">
          <el-button size="mini" @click="rest" v-if="title!='详情'">重置</el-button>
          <el-button type="primary" size="mini" @click="save">保存</el-button>
        </div>
      </div>
      <el-dialog title="选择" :visible.sync="visible2" append-to-body="true" width="700px">
        <div v-if="form.limitType==2">
          <el-form :model="productSearch" :inline="inline">
            <el-form-item label="商品ID">
              <el-input placeholder="商品ID" v-model="productSearch.id" />
            </el-form-item>
            <el-form-item label="商品名称">
              <el-input placeholder="商品名称" v-model="productSearch.name" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="searchProduct">搜索</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="productList">
            <el-table-column label="ID" width="50px">
              <template slot-scope="scope">
                <span>{{scope.row.id}}</span>
              </template>
            </el-table-column>
            <el-table-column label="名称">
              <template slot-scope="scope">
                <span class="name">{{scope.row.name}}</span>
              </template>
            </el-table-column>
            <el-table-column label="图片">
              <template slot-scope="scope">
                <img :src="scope.row.mainImage" style="width:50px;height:50px" />
              </template>
            </el-table-column>
            <el-table-column label="价格">
              <template slot-scope="scope">
                <span class="name">{{scope.row.price}}</span>
              </template>
            </el-table-column>
            <el-table-column label="库存">
              <template slot-scope="scope">
                <span class="name">{{scope.row.stock}}</span>
              </template>
            </el-table-column>
            <el-table-column label="选择">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="choice(scope.row)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="form.limitType==1">
          <el-table :data="activityData">
            <el-table-column label="ID" width="50px">
              <template slot-scope="scope">
                <span>{{scope.row.id}}</span>
              </template>
            </el-table-column>
            <el-table-column label="活动名称">
              <template slot-scope="scope">
                <span class="name">{{scope.row.name}}</span>
              </template>
            </el-table-column>
            <el-table-column label="选择">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="choice(scope.row)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
import {
  list,
  add,
  updateStatus,
  del,
  detail,
  productList,
  activityList,
  update
} from "@/api/coupon.js";
import { validateAmount } from "@/utils/validate.js";
import { format } from "@/utils/dateUtil.js";
export default {
  data() {
    return {
      inline:true,
      activityData: [],
      productList: [],
      title: "添加",
      index: 1,
      pageSize: 10,
      tableData: [],
      total: 0,
      visible2: false,
      visible: false,
      choiceText: "",
      productSearch: {
        id: "",
        name: ""
      },
      searchForm: {
        type: "null",
        limitType: "null",
        title: ""
      },
      form: {
        time: [],
        title: "",
        type: 0,
        limitType: 0,
        amount: 0,
        conditionAmount: 0,
        expireType: 0,
        limitSendTotal: 1,
        limitPre: 1,
        objId: null,
        expireDays: 1,
        expireStartTime: "",
        expireEndTime: "",
        explainText: ""
      },
      rules: {
        title: [
          { required: true, message: "请输入优惠券名称", trigger: "blur" },
          { min: 5, max: 30, message: "长度5 ~ 30个字符", trigger: "blur" }
        ],
        amount: [
          { required: true, validator: validateAmount, trigger: "blur" }
        ],
        type: [
          {
            required: true,
            type: "number",
            message: "请选择类型",
            trigger: "change"
          }
        ],
        limitType: [
          {
            required: true,
            type: "number",
            message: "请选择类型",
            trigger: "change"
          }
        ],
        expireType: [
          {
            required: true,
            type: "number",
            message: "请选择类型",
            trigger: "change"
          }
        ],
        explainText: [
          { required: true, message: "请输入优惠券说明", trigger: "blur" },
          { min: 5, max: 200, message: "长度5 ~ 30个字符", trigger: "blur" }
        ],
        limitSendTotal: [
          {
            required: true,
            type: "number",
            message: "请输入发放总量",
            trigger: "blur"
          }
        ],
        limitPre: [
          {
            required: true,
            type: "number",
            message: "请输入每人领取",
            trigger: "blur"
          }
        ]
      }
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    choice(data) {
      this.visible2 = false;
      var s = "已选择[id:" + data.id + "]" + data.name;
      this.form.objId = data.id;
      this.choiceText = s.substring(0, 15);
    },
    getActivityList() {
      activityList().then(res => {
        this.activityData = res.data;
      });
    },
    searchProduct() {
      productList(this.productSearch.id, this.productSearch.name).then(res => {
        this.productList = res.data;
      });
    },
    openAddForm() {
      this.visible = true;
      this.title = "添加";
      this.couponId = null;
      this.rest();
    },
    openChoise() {
      this.visible2 = true;
      if (this.form.limitType == 1) {
        this.getActivityList();
      }

      if (this.form.limitType == 2) {
        this.searchProduct();
      }
    },
    query(id) {
      this.title = "修改";
      this.visible = true;
      this.couponId = id;
      detail(id).then(res => {
        this.form = res.data;
        var time = [];
        time.push(new Date(res.data.expireStartTime.replace(/-/g, "/")));
        time.push(new Date(res.data.expireEndTime.replace(/-/g, "/")));
        this.form.time = time;
      });
    },
    updateStatus(id) {
      updateStatus(id).then(res => {
        this.getData();
      });
    },
    rest() {
      this.form = {
        time: [],
        title: "",
        type: 0,
        limitType: 0,
        amount: 0,
        conditionAmount: 0,
        expireType: 0,
        limitSendTotal: 1,
        limitPre: 1,
        objId: null,
        expireDays: 1,
        expireStartTime: "",
        expireEndTime: "",
        explainText: ""
      };
    },
    save() {
      if (this.couponId == null) {
        this.$refs["from"].validate(valid => {
          if (valid) {
            var startTiem = null;
            var endTime = null;
            if (this.form.expireType == 0) {
              startTiem = format(this.form.time[0]);
              endTime = format(this.form.time[1]);
            }

            add(
              this.form.title,
              this.form.type,
              this.form.limitType,
              this.form.amount,
              this.form.conditionAmount,
              this.form.expireType,
              this.form.limitSendTotal,
              this.form.limitPre,
              this.form.objId,
              this.form.expireDays,
              startTiem,
              endTime,
              this.form.explainText
            ).then(res => {
              this.$message({
                message: "添加成功",
                type: "success"
              });
              this.getData();
              this.rest();
              this.visible = false;
            });
          }
        });
      } else {
        update(
          this.couponId,
          this.form.explainText,
          this.form.limitSendTotal,
          this.form.limitPre
        ).then(res => {
          this.$message({
            message: "修改成功",
            type: "success"
          });
          this.getData();
          this.rest();
          this.visible = false;
        });
      }
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getData();
    },
    handleCurrentChange(page) {
      this.index = page;
      this.getData();
    },
    /**
     * 删除数据
     */
    del(id) {
      del(id).then(res => {
        this.getData();
      });
    },
    /**
     * 获取数据
     */
    getData() {
      var type = this.searchForm.type == "null" ? null : this.searchForm.type;
      var limitType =
        this.searchForm.limitType == "null" ? null : this.searchForm.limitType;

      list(
        type,
        limitType,
        this.searchForm.title,
        this.index,
        this.pageSize
      ).then(res => {
        if (res.data.records != null) {
          for (var i = 0; i < res.data.records.length; i++) {
            if (res.data.records[i].status != 1) {
              res.data.records[i].s = 0;
            } else {
              res.data.records[i].s = 1;
            }
          }
        }
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
    }
  }
};
</script>
<style scoped>
.name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.bottom {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding-right: 30px;
  box-sizing: border-box;
}
.form {
  width: 700px;
}
label {
  color: #606266;
  font-size: 14px;
}
.head_left {
  display: flex;
  align-items: center;
}
.head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 100%;
  width: 100%;
  margin-bottom: 15px;
  height: 100px;
  background-color: #ffffff;
  padding: 0 20px;
  box-sizing: border-box;
}
.page {
  width: 100%;
  display: flex;
  justify-content: center;
  height: 100px;
  align-items: center;
}
</style>